#include "fs_TexturePool.h"

#include <iostream>
#include "SOIL.h"
#define FS_SOIL_DEFAULT_FLAGS (SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_TEXTURE_REPEATS)

fs_TexturePool* fs_TexturePool::m_instance = NULL;

fs_TexturePool *fs_TexturePool::Instance(void) {
	if(!m_instance)
		m_instance = new fs_TexturePool();

	return m_instance;
}

void fs_TexturePool::Destroy() {
	delete m_instance;
	m_instance = NULL;
}

fs_TexturePool::~fs_TexturePool(void) {
	// Unbind all of the textures from openGL
	vector<fs_TextureAssociation>::iterator it;

	for(it = loadedTextures.begin(); it != loadedTextures.end(); ++it)
		glDeleteTextures(1, &((*it).textureID));
}

GLuint fs_TexturePool::loadTexture(string filename) {
	// See if the texture has already been loaded
	vector<fs_TextureAssociation>::iterator it;

	for(it = loadedTextures.begin(); it != loadedTextures.end(); ++it) {
		if((*it).textureName.compare(filename) == 0) {
			++((*it).loadCount);

			return (*it).textureID;
		}
	}

	// Attempt to load the texture using SOIL
	fs_TextureAssociation tAss;
	tAss.textureName = filename;
	tAss.textureID = SOIL_load_OGL_texture(filename.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, FS_SOIL_DEFAULT_FLAGS);
	if(tAss.textureID == 0) {
		cout << "SOIL loading error: " << SOIL_last_result() << endl;
		return 0;
	}

	tAss.loadCount = 1;
	return tAss.textureID;
}

void fs_TexturePool::unloadTexture(GLuint glTextureID) {
	if(glTextureID == 0)
		return;

	// Find the texture ID; decrease the load count
	// if the load count is zero, unload it from
	// openGL and the loadedTextures vector
	vector<fs_TextureAssociation>::iterator it;
	for(it = loadedTextures.begin(); it != loadedTextures.end(); ++it) {
		if(glTextureID == (*it).textureID) {
			--((*it).loadCount);

			if((*it).loadCount == 0) {
				glDeleteTextures(1, &glTextureID);
				loadedTextures.erase(it);
			}

			return;
		}
	}

	cout << "Warning: Tried to unload a non-existent textureID.\n";
}